package controllers;

import helpers.CrawlerHelper;
import helpers.FileHelper;
import helpers.IpHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.RecentlyDomain;

import debugs.DomainDebug;

import models.DomainIpModel;
import models.DomainModel;

import entities.Domain;
import entities.DomainIp;
import entities.IpAddress;

public class DomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");

		DomainModel domainModel = DomainModel.getInstance();
		DomainIpModel domainIpModel = DomainIpModel.getInstance();
		Domain domain = null;
		IpAddress ipAddress = null;
		DomainIp domainIp = null;
		
		if (UrlHelper.checkDomain(name)) {
			name = UrlHelper.getMainDomain(name);
			
			domain = domainModel.get(name);
			if (domain == null) {
				try {
					domain = CrawlerHelper.getDomainIp(name);
					if (domain != null && !domain.getIp().isEmpty()) {
						domainModel.insert(domain);
					}
				} catch (Exception e) {
				}
				
			}
			
			if (domain != null && domain.getStatus() == -1) {
				response.sendError(404);
				return;
			}
			
			if (domain != null && !domain.getIp().isEmpty()) {
				if (IpHelper.checkIsIp(domain.getIp())) {
					ipAddress = FileHelper.getByFileName(domain.getIp());
					if (ipAddress == null) {
						try {
							ipAddress = CrawlerHelper.getIp(domain.getIp());
							FileHelper.saveToObject(ipAddress);
						} catch (Exception e) {
						}
						
					}
					domainIpModel.insert(domain.getIp(), domain.getDomain());
					
					domainIp = domainIpModel.get(domain.getIp());
					
				}
			}
			if (domain != null) {
				RecentlyDomain.insert(name);
			}
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("name", name);
		request.setAttribute("domain", domain);
		request.setAttribute("ipAddress", ipAddress);
		request.setAttribute("domainIp", domainIp);
		try {
			request.getRequestDispatcher("/pages/domain.jsp").forward(request, response);
		} catch (ServletException e) {
			/*response.sendRedirect("/");
			return;*/
		}
	}
}
